//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;

@WebFilter(
        filterName = "loginCheckFilter",
        urlPatterns = {"/*"}
)
public class LoginCheckFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    public LoginCheckFilter() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String[] urls = new String[]{"/employee/login", "/employee/logout", "/backend/**", "/front/**", "/common/**", "/user/sendMsg", "/user/login"};
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截的请求：{}", requestURI);
        boolean check = this.check(urls, requestURI);
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
        } else {
            Long userId;
            if (request.getSession().getAttribute("employee") != null) {
                log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("employee"));
                userId = (Long)request.getSession().getAttribute("employee");
                BaseContext.setCurrentId(userId);
                filterChain.doFilter(request, response);
            } else if (request.getSession().getAttribute("user") != null) {
                userId = (Long)request.getSession().getAttribute("user");
                BaseContext.setCurrentId(userId);
                filterChain.doFilter(request, response);
            } else {
                log.info("用户未登录");
                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            }
        }
    }

    public boolean check(String[] urls, String requestURI) {
        String[] var3 = urls;
        int var4 = urls.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String url = var3[var5];
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }

        return false;
    }
}
